import re
from rest_framework import serializers

from areas.models import Area
from users.models import Address


class AreaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Area
        fields = '__all__'


class AddressSerializer(serializers.ModelSerializer):
    #id反序列化
    province_id = serializers.IntegerField(min_value=1,write_only=True)
    city_id = serializers.IntegerField(min_value=1,write_only=True)
    district_id = serializers.IntegerField(min_value=1,write_only=True)

    # 序列化
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)

    class Meta:
        model = Address
        fields = ('title', 'receiver', 'place', 'mobile','id',
                  "province_id","city_id","district_id","province","city","district")

    def validate_mobile(self,value):
        if not re.match(r"^1[3-9]{9}\d$",value):
            raise serializers.ValidationError('手机号格式不正确')
        return value


    def validate(self,value):
        print(value)
        return value


    def create(self, validated_data):
        #获取用户对象
        validated_data['user']=self.context['request'].user
        address = Address.objects.create(**validated_data)
        return address












